# -*- coding;utf-8 -*-
"""
File name : ConvertQuestionList2RenderContext.py.PY
Program IDE : PyCharm
Create file time: 2023/5/28 23:00
File Create By Author : 朱清闯
"""
'''文件夹路径符号可能需要修改，利用os'''
import re
from docxtpl import DocxTemplate, InlineImage
from docx.shared import Mm


def extract_file(url):
    pattern = re.compile(r'(upload/[\d]+\.jpg)')  # 用于提取图片url中upload/x.jpg部分
    if len(url) > 0:
        temp_pictures = url.pictures.split("-")
        return re.search(pattern, temp_pictures).groups()


def list_2_dictionary(question_list: list):
    tpl = DocxTemplate('templates/paper.docx')
    map_question_type_dict = {"选择题": "choice_question_list", '填空题': "cloze_question_list"}  # 把题目中的选择题转换成
    context_dict = {'has_choice': True, 'choice_question_list': [], 'has_cloze': True, 'cloze_question_list': []}
    index_dict = {'choice_question_list': 0, 'cloze_question_list': 0}
    for question in question_list:
        q_type = map_question_type_dict[question.type]

        context_dict[q_type].append({"content": question["content"], "answer": question["answer"],
                                     "explain": question["explain"]})
        index_dict[q_type] += 1
        if len(question['pictures']) > 0:
            pictures = extract_file(question['pictures'])
            for picture in pictures:
                context_dict[q_type][index_dict[q_type]]["pictures"].append(InlineImage(tpl, "./"+picture, width=Mm(40)))
        if len(question['pictures_explain']) > 0:
            pictures = extract_file(question['pictures_explain'])
            for picture in pictures:
                context_dict[q_type][index_dict[q_type]]["pictures_explain"].append(InlineImage(tpl, "./" + picture, width=Mm(40)))
    if len(context_dict["choice_question_list"]) == 0:
        context_dict['has_choice'] = False
    if len(context_dict["cloze_question_list"]) == 0:
        context_dict['has_cloze'] = False
    return context_dict
